<template>
  <el-card class="report-list-card">
    <!-- 添加页面标题 -->
    <div class="page-header">
      <div class="page-title">出厂报告列表</div>
      <div class="page-subtitle">管理所有出厂检验报告</div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline class="filter-form">
        <el-form-item label="客户名称">
          <el-input 
            v-model="filterForm.customer" 
            placeholder="请输入客户名称"
            clearable
            style="width: 250px;"
            @input="handleFilter"
          />
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input 
            v-model="filterForm.plate" 
            placeholder="请输入车牌号"
            clearable
            style="width: 200px;"
            @input="handleFilter"
          />
        </el-form-item>
        <el-form-item label="检验人">
          <el-input 
            v-model="filterForm.inspector" 
            placeholder="请输入检验人"
            clearable
            style="width: 180px;"
            @input="handleFilter"
          />
        </el-form-item>
        <el-form-item label="报告日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 350px;"
            @change="handleFilter"
          />
        </el-form-item>

        <el-form-item>
                  <el-button type="primary" @click="handleFilter">筛选</el-button>
        <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="report-list-header">
      <div class="header-left">
        <div class="filter-summary">
          <span v-if="hasActiveFilters" class="filter-info">
            已筛选 {{ filteredReports.length }} 条记录
            <el-button type="link" @click="resetFilter" class="clear-filter-btn">
              清除筛选
            </el-button>
          </span>
        </div>
      </div>
      <div class="header-right">
        <el-button 
          v-if="selectedReports.length > 0"
          type="danger" 
          size="large"
          @click="batchDelete"
          class="batch-delete-btn"
        >
          批量删除 ({{ selectedReports.length }})
        </el-button>

        <el-button type="primary" size="large" @click="onCreate" class="create-btn">
          新建报告
        </el-button>
        <el-button 
          type="warning" 
          size="large"
          @click="openStandardDialog"
          class="standard-btn"
        >
          查看技术标准
        </el-button>
      </div>
    </div>
    <el-table
      :data="uniqueReports"
      style="width:100%"
      stripe
      highlight-current-row
      :header-cell-style="{fontWeight: 'bold', fontSize: '16px', background:'#f5f7fa'}"
      :row-class-name="tableRowClassName"
      empty-text="暂无出厂报告"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >

      <el-table-column type="selection" width="55" />
      <el-table-column prop="code" label="报告编号" min-width="200" />
      <el-table-column prop="customer" label="客户名称" min-width="200" />
      <el-table-column prop="plate" label="车牌号" min-width="150" />
      <el-table-column prop="inspector" label="检验人" min-width="120" />
      <el-table-column prop="createdAt" label="报告生成时间" min-width="200" />
      <el-table-column label="操作" min-width="250">
        <template #default="scope">
          <el-button size="small" type="primary" @click="goDetail(scope.row)">查看/编辑</el-button>
          <el-button size="small" type="danger" @click="deleteReport(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="totalReports > pageSize"
      style="margin: 24px 0 0 0; text-align: right;"
      background
      layout="prev, pager, next, jumper"
      :total="totalReports"
      :page-size="pageSize"
      v-model:current-page="currentPage"
    />
  </el-card>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import AV from '../leancloud'

const router = useRouter()
const reports = ref([])
const currentPage = ref(1)
const pageSize = 10
const selectedReports = ref([])
const tableRef = ref(null)

// 筛选表单数据
const filterForm = ref({
  customer: '',
  plate: '',
  inspector: '',
  dateRange: []
})

// 筛选后的报告数据
const filteredReports = ref([])

// 先计算去重后的所有数据
const allUniqueReports = computed(() => {
  const map = new Map()
  reports.value.forEach(r => {
    if (!map.has(r.code)) map.set(r.code, r)
  })
  return Array.from(map.values())
})

// 筛选数据
const filteredUniqueReports = computed(() => {
  let filtered = allUniqueReports.value
  
  // 客户名称筛选
  if (filterForm.value.customer) {
    filtered = filtered.filter(report => 
      report.customer && report.customer.toLowerCase().includes(filterForm.value.customer.toLowerCase())
    )
  }
  
  // 车牌号筛选
  if (filterForm.value.plate) {
    filtered = filtered.filter(report => 
      report.plate && report.plate.toLowerCase().includes(filterForm.value.plate.toLowerCase())
    )
  }
  
  // 检验人筛选
  if (filterForm.value.inspector) {
    filtered = filtered.filter(report => 
      report.inspector && report.inspector.toLowerCase().includes(filterForm.value.inspector.toLowerCase())
    )
  }
  
  // 日期范围筛选
  if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.value.dateRange
    filtered = filtered.filter(report => {
      if (!report.date) return false
      const reportDate = new Date(report.date)
      const start = new Date(startDate)
      const end = new Date(endDate)
      return reportDate >= start && reportDate <= end
    })
  }
  
  return filtered
})

// 然后基于筛选后的数据进行分页
const uniqueReports = computed(() => {
  const arr = filteredUniqueReports.value
  const start = (currentPage.value - 1) * pageSize
  return arr.slice(start, start + pageSize)
})

// 总数据量用于分页
const totalReports = computed(() => filteredUniqueReports.value.length)

// 是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return filterForm.value.customer || 
         filterForm.value.plate || 
         filterForm.value.inspector ||
         (filterForm.value.dateRange && filterForm.value.dateRange.length === 2)
})



async function fetchReports() {
  const query = new AV.Query('FactoryReport')
  query.descending('createdAt')
  const res = await query.find()
  reports.value = res.map(r => {
    const baseInfo = r.get('baseInfo') || {}
    // 使用保存的报告编号
    const reportCode = baseInfo.reportCode || `JL-${r.id.slice(-8)}`
    
    // 获取检验人员信息
    let inspector = baseInfo.inspectorName || '-'
    
    // 如果检验人员信息为空，显示"未设置"
    if (!inspector || inspector === '-') {
      inspector = '未设置'
    }
    
    return {
      id: r.id,
      code: reportCode,
      customer: baseInfo.customer,
      plate: baseInfo.plate || '-',
      date: baseInfo.date,
      product: baseInfo.product || '-',
      inspector: inspector,
      createdAt: r.createdAt ? new Date(r.createdAt).toLocaleString() : '-'
    }
  })
}
onMounted(fetchReports)

// 处理筛选
function handleFilter() {
  // 重置到第一页
  currentPage.value = 1
  // 清空选择
  selectedReports.value = []
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

// 重置筛选
function resetFilter() {
  filterForm.value = {
    customer: '',
    plate: '',
    inspector: '',
    dateRange: []
  }
  handleFilter()
}
function goDetail(row) {
  router.push(`/factory-report/${row.id}`)
}
function onCreate() {
  router.push('/factory-report/new')
}
function openStandardDialog() {
  router.push('/standard-maintain')
}
function tableRowClassName({row, rowIndex}) {
  return rowIndex % 2 === 1 ? 'report-row-alt' : ''
}

// 处理表格选择变化
function handleSelectionChange(selection) {
  selectedReports.value = selection
}

// 删除单个报告
async function deleteReport(report) {
  try {
    await ElMessageBox.confirm(
      `确定要删除报告"${report.code}"吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const query = new AV.Query('FactoryReport')
    query.equalTo('objectId', report.id)
    const result = await query.find()
    
    if (result.length > 0) {
      await AV.Object.destroyAll(result)
      ElMessage.success('报告删除成功')
      await fetchReports() // 重新加载数据
    } else {
      ElMessage.error('未找到要删除的报告')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}



// 批量删除报告
async function batchDelete() {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请先选择要删除的报告')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedReports.value.length} 个报告吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const reportIds = selectedReports.value.map(report => report.id)
    const query = new AV.Query('FactoryReport')
    query.containedIn('objectId', reportIds)
    const results = await query.find()
    
    if (results.length > 0) {
      await AV.Object.destroyAll(results)
      ElMessage.success(`成功删除 ${results.length} 个报告`)
      selectedReports.value = [] // 清空选择
      await fetchReports() // 重新加载数据
    } else {
      ElMessage.error('未找到要删除的报告')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败：' + error.message)
    }
  }
}


</script>
<style scoped>
.report-list-card {
  width: 100%;
  margin: 32px auto;
  box-shadow: 0 4px 24px 0 rgba(22,119,255,0.08), 0 1.5px 6px 0 rgba(0,0,0,0.04);
  border-radius: 16px;
  padding: 32px 24px;
}
.page-header {
  margin-bottom: 20px;
  text-align: center;
}

/* 页面标题样式已移至全局样式文件 */

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  width: 100%;
}

.filter-form {
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-form .el-form-item {
  margin-bottom: 16px;
  margin-right: 0;
  flex-shrink: 0;
}

.filter-form .el-form-item__label {
  font-weight: 600;
  color: #333;
}

.filter-summary {
  display: flex;
  align-items: center;
}

.filter-info {
  font-size: 14px;
  color: #666;
  background: #e6f7ff;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #91d5ff;
}

.clear-filter-btn {
  margin-left: 8px;
  color: #1677ff;
  font-size: 12px;
}

.clear-filter-btn:hover {
  color: #409eff;
}

.report-list-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-left h2 {
  font-size: 24px;
  font-weight: 700;
  color: #1677ff;
  margin: 0 0 4px 0;
}

.header-left .subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
  font-weight: 400;
}

.header-right {
  display: flex;
  align-items: center;
}

.create-btn {
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
  transition: all 0.3s ease;
  min-width: 120px;
}

/* 强制覆盖Element Plus按钮的内部结构 */
.create-btn :deep(.el-button__content) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100%;
  text-align: center;
}

.create-btn :deep(span:first-child) {
  margin-right: 4px;
  font-weight: bold;
  font-size: 16px;
}

.create-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
}

.batch-delete-btn {
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
  transition: all 0.3s ease;
  margin-right: 12px;
}

.batch-delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}



.standard-btn {
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(245, 158, 11, 0.2);
  transition: all 0.3s ease;
  min-width: 120px;
  margin-left: 12px;
}

/* 强制覆盖Element Plus按钮的内部结构 */
.standard-btn :deep(.el-button__content) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100%;
  text-align: center;
}

.standard-btn :deep(span:first-child) {
  margin-right: 4px;
  font-weight: bold;
  font-size: 16px;
}

.standard-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}
.el-table {
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
  border: 1px solid #f0f0f0;
}

.el-table th {
  font-weight: 600;
  font-size: 15px;
  background: #fafbfc;
  color: #333;
  border-bottom: 1px solid #e8e8e8;
}
.el-table .el-button {
  border-radius: 6px;
  font-weight: 500;
}
.el-table .el-button[type="primary"] {
  background: #1677ff;
  border-color: #1677ff;
}
.el-table .el-button[type="primary"]:hover {
  background: #409eff;
  border-color: #409eff;
}


.el-table .report-row-alt {
  background: #f8fbff;
}
.el-pagination {
  margin-top: 18px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-form .el-form-item {
    flex: 1 1 calc(50% - 8px);
  }
}

@media (max-width: 700px) {
  .page-header {
    text-align: left;
    padding-left: 10px;
    padding-bottom: 5px;
  }
  
  /* 筛选区域移动端样式 */
  .filter-section {
    padding: 16px;
  }
  
  .filter-form {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .filter-form .el-form-item {
    margin: 0;
    width: 100%;
    flex: 1 1 100%;
  }
  
  .filter-form .el-input,
  .filter-form .el-select,
  .filter-form .el-date-picker {
    width: 100% !important;
  }
  
  /* 页面标题样式已移至全局样式文件 */
  .report-list-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  .header-right {
    width: 100%;
    justify-content: flex-start;
    gap: 8px;
    flex-wrap: wrap;
  }
  .create-btn, .standard-btn, .batch-delete-btn {
    min-width: 100px;
    padding: 8px 16px;
    font-size: 14px;
    flex: 1;
  }
  .el-table {
    font-size: 13px;
    min-width: 600px;
    overflow-x: auto;
    display: block;
  }
  .el-table__body-wrapper {
    overflow-x: auto !important;
  }
  .el-button, .el-input, .el-select {
    font-size: 16px !important;
    min-height: 38px !important;
  }
  .el-pagination {
    font-size: 15px;
    padding: 8px 0;
  }
}

</style> 